package com.gin.kotlin.no_gay_alliance.fragment.replyhistory

import android.os.Bundle
import android.view.View
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.ReplyHistoryArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.database.entity.ReplyHistory
import com.gin.kotlin.no_gay_alliance.databinding.FragmentReplyHistoryPageBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat

/**
 * 抽象回复历史Fragment，负责查询逻辑
 * @property argument ReplyHistoryArgument
 */
abstract class AbstractReplyHistoryPageFragment : AbstractBindingFragment<FragmentReplyHistoryPageBinding>() {
    private lateinit var argument: ReplyHistoryArgument

    override fun handleArguments(bundle: Bundle) {
        super.handleArguments(bundle)
        this.argument = parseBundle(bundle, ReplyHistoryArgument::class.java.simpleName, ReplyHistoryArgument::class.java)
    }

    override fun onCreateView() {
        val b = this.b ?: return
        initRenderComponent(b)
        page()
    }

    /**
     * 初始化渲染组件
     * @param b FragmentReplyHistoryPageBinding
     */
    abstract fun initRenderComponent(b: FragmentReplyHistoryPageBinding)




    override fun onResume() {
        super.onResume()
        handler?.sendMessage(HandlerMessageWhat.PAGE_UPDATED, argument.page)
    }

    private fun page() {
        val b = this.b ?: return

        b.swipeRefreshLayout.isRefreshing = true

        val data = App.INSTANCE.database.replyHistoryDao()
            .list(argument.buildSql("select * from ReplyHistory where %s order by uuid desc limit ${(argument.page - 1) * argument.size},${argument.size}"))

        if (data.isNullOrEmpty()) {
            b.tvWarning.visibility = View.VISIBLE
            b.swipeRefreshLayout.removeAllViews()
        } else {
            b.tvWarning.visibility = View.GONE
            // 渲染数据
            render(data)
        }

        b.swipeRefreshLayout.isRefreshing = false
    }

    /**
     * 渲染数据
     * @param data List<ReplyHistory>?
     */
    abstract fun render(data: List<ReplyHistory>)

}